package com.cy.sqlSession;

import com.cy.pojo.Configuration;
import com.cy.pojo.MappedStatement;
import com.cy.pojo.SqlCommandType;

import java.beans.IntrospectionException;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.util.List;

public class DefaultSession implements SqlSession {

    Configuration configuration;

    public DefaultSession(Configuration configuration) {
        this.configuration = configuration;
    }


    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws SQLException, IntrospectionException, NoSuchFieldException, InvocationTargetException, IllegalAccessException, InstantiationException {

        //完成对Executor的调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> query = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);
        return (List<E>) query;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws SQLException, IntrospectionException, NoSuchFieldException, InvocationTargetException, IllegalAccessException, InstantiationException {
        List<Object> result = selectList(statementId, params);
        if (result.size() == 1){
            return (T) result.get(0);
        }
        else {
            throw new RuntimeException("查询结果为空或大于1");
        }
    }

    @Override
    public <T> int insert(String statementId, Object... object) throws SQLException, NoSuchFieldException, IllegalAccessException {
        return update(statementId, object);
    }

    @Override
    public <T> int update(String statementId, Object... object) throws SQLException, NoSuchFieldException, IllegalAccessException {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        return simpleExecutor.update(configuration, configuration.getMappedStatementMap().get(statementId), object);
    }

    @Override
    public <T> int delete(String statementId, Object... object) throws SQLException, NoSuchFieldException, IllegalAccessException {
        return update(statementId, object);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //jdb动态代理，为dao接口生成代理对象，并返回
        //代理对象调用接口中任意方法，都会执行invoke方法
        Object proxyInstance = Proxy.newProxyInstance(DefaultSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            //proxy:当前代理对象的引用
            //method:调用的方法
            //传入的参数
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //根据不同情况调用selectList或者selectOne

                //准备statementId,  =  namespace.id
                String className = method.getDeclaringClass().getName();
                String methodName = method.getName();
                String statementId = className + "." + methodName;
                //准备参数2，params，就是args
                //获取调用参数的返回值，根据返回值来判断是调用selectList或者selectOne
                //获取到MappedStatement，获取对应的SQL类型
                MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
                SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
                //判断类型，做对应处理调用
                switch (sqlCommandType) {
                    case INSERT:
                        return insert(statementId, args);
                    case UPDATE:
                        return update(statementId, args);
                    case DELETE:
                        return delete(statementId, args);
                    case SELECT:
                        Type genericReturnType = method.getGenericReturnType();
                        if (genericReturnType instanceof ParameterizedType) {
                            return selectList(statementId, args);
                        } else {
                            return selectOne(statementId, args);
                        }
                    default:
                        throw new Exception("找不到该标签类型");
                }
            }
        });

        return (T) proxyInstance;
    }
}
